/*
 * @Description: 你的代码我的心
 * @Author: GGB
 * @Date: 2021-11-03 11:29:09
 * @LastEditors: GGB
 * @LastEditTime: 2022-09-14 15:05:29
 */
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import { VueAxios } from './axios'
import { useGlobSetting } from '@/hooks/setting'
import { getToken } from './auth'
const globSetting = useGlobSetting()
const urlPrefix = globSetting.urlPrefix
// 创建 axios 实例
const service = axios.create({
  // 服务端api地址
  baseURL: globSetting.apiUrl,
  timeout: 25 * 1000, // 请求超时时间，25秒, 如果上传大文件需要更长
})

// 接口请求拦截
service.interceptors.request.use((config) => {
  // 设置每个请求的Content-Type
  // config.headers['Content-Type'] = 'application/json;charset=utf-8'
  // 添加请求接口--前缀
  config.url = `${urlPrefix}${config.url}`
  // storage.set(ACCESS_TOKEN,'')

  const token = getToken()
  // 让每个请求携带当前用户token
  if (token) {
    config.headers['Access-Token'] = token
  }
  return config
})

// 接口响应拦截
service.interceptors.response.use(
  (response) => {
    const result = response.data
    // result.status [ 200正常 500有错误 401未登录 403没有权限访问 ]
    // api报错信息
    if (result.status === 500) {
      message.error(result.message, 1.8)
      return Promise.reject(result)
    }

    // 鉴权失败: 未登录
    if (result.status === 401 || result.code === -1) {
      // store.dispatch('Logout').then(() => {
      //   notification.error({
      //     message: '错误',
      //     description: result.message,
      //     duration: 3
      //   })
      //   setTimeout(() => {
      //     window.location.reload()
      //   }, 1200)
      // })
      //  // TODO 登出会出现一个问题，token过期登出无效--
      // store.dispatch('Logout')
      store.dispatch('LogoutWithoutToken').then(() => {
        notification.error({
          message: '错误',
          description: result.message,
          duration: 3,
        })
        setTimeout(() => {
          window.location.reload()
        }, 1200)
      })
      return Promise.reject(result)
    }
    /**
     * 统一错误处理
     */
    if (result.code !== 0) {
      message.error(result.message, 1.8)
      return Promise.reject(result)
    }
    return result
  },
  (error) => {
    // 网络请求出错
    const errMsg = ((error.response || {}).data || {}).message || '请求出现错误，请稍后再试'
    notification.error({
      message: '网络请求出错',
      description: errMsg,
      duration: 3,
    })
    return Promise.reject(error)
  }
)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  },
}

export { installer as VueAxios, service as axios }
